package com.dotstone.chipism.ui.security.me;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dotstone.chipism.R;
import com.dotstone.chipism.activity.BaseActivity;
import com.dotstone.chipism.activity.MainActivity;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.lib.funsdk.support.FunSupport;
import com.lib.funsdk.support.FunWifiPassword;
import com.lib.funsdk.support.OnFunDeviceWiFiConfigListener;
import com.lib.funsdk.support.models.FunDevice;
import com.lib.funsdk.support.utils.DeviceWifiManager;
import com.lib.funsdk.support.utils.MyUtils;
import com.lib.funsdk.support.utils.StringUtils;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

public class CameraConnectActivity extends BaseActivity implements OnFunDeviceWiFiConfigListener {

    private LinearLayout mBackL;
    private LinearLayout lly_second;
    private TextView tv_statusBar_mian;
    private TextView tv_time;
    private TextView tv_connecting;
    private String deviceName;
    private Button btn_cancel;
    private boolean isRun = true;
    private int time = 120;

    @Override
    public void widgetClick(View v) {
        switch (v.getId()){
            //返回
            case R.id.back_layout:
                finish();
                break;
            //取消
            case R.id.btn_cancel:
                startActivity(MainActivity.class);
                break;
        }
    }

    @Override
    public void initParms(Bundle parms) {

    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_camera_connect;
    }

    @Override
    public void initView(View view) {
        mBackL = $(R.id.back_layout);
        btn_cancel = $(R.id.btn_cancel);
        tv_connecting = $(R.id.tv_connecting);
        tv_statusBar_mian = $(R.id.tv_statusBar_mian);
        lly_second = $(R.id.lly_second);
        tv_time = $(R.id.tv_time);
    }

    @Override
    public void setListener() {
        mBackL.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        boolVersion();
    }

    // 开始快速配置
    private void startQuickSetting() {

        try {
            WifiManager wifiManage = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManage.getConnectionInfo();
            DhcpInfo wifiDhcp = wifiManage.getDhcpInfo();
            if ( null == wifiInfo ) {
                showToast("111");
                return;
            }

            String ssid = wifiInfo.getSSID().replace("\"", "");
            if ( StringUtils.isStringNULL(ssid) ) {
                showToast(getString(R.string.device_opt_set_wifi_info_error));
                return;
            }

            ScanResult scanResult = DeviceWifiManager.getInstance(this).getCurScanResult(ssid);
            if ( null == scanResult ) {
                showToast(getString(R.string.device_opt_set_wifi_info_error));
                return;
            }

            int pwdType = MyUtils.getEncrypPasswordType(scanResult.capabilities);
            String wifiPwd = getIntent().getStringExtra("password");

            if ( pwdType != 0 && StringUtils.isStringNULL(wifiPwd) ) {
                // 需要密码
                showToast(getString(R.string.device_opt_set_wifi_info_error));
                return;
            }

            StringBuffer data = new StringBuffer();
            data.append("S:").append(ssid).append("P:").append(wifiPwd).append("T:").append(pwdType);

            String submask;
            if (wifiDhcp.netmask == 0) {
                submask = "255.255.255.0";
            } else {
                submask = MyUtils.formatIpAddress(wifiDhcp.netmask);
            }

            String mac = wifiInfo.getMacAddress();
            StringBuffer info = new StringBuffer();
            info.append("gateway:").append(MyUtils.formatIpAddress(wifiDhcp.gateway)).append(" ip:")
                    .append(MyUtils.formatIpAddress(wifiDhcp.ipAddress)).append(" submask:").append(submask)
                    .append(" dns1:").append(MyUtils.formatIpAddress(wifiDhcp.dns1)).append(" dns2:")
                    .append(MyUtils.formatIpAddress(wifiDhcp.dns2)).append(" mac:").append(mac)
                    .append(" ");


            FunSupport.getInstance().startWiFiQuickConfig(ssid,
                    data.toString(), info.toString(),
                    MyUtils.formatIpAddress(wifiDhcp.gateway),
                    pwdType, 0, mac, -1);

            FunWifiPassword.getInstance().saveWifiPassword(ssid, wifiPwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopQuickSetting() {
        FunSupport.getInstance().stopWiFiQuickConfig();
    }


    @Override
    public void doBusiness(Context mContext) {
        tv_time.setText(time + "");
        //开始一个计时线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRun){
                    SystemClock.sleep(1000);
                    if (time > 0) {
                        if (isRun) {
                            time--;
                            handler.sendEmptyMessageDelayed(0, 0);
                        }
                    } else {
                        isRun = false;
                    }
                }
            }
        }).start();

        FunSupport.getInstance().registerOnFunDeviceWiFiConfigListener(this);
        //开始配置
        startQuickSetting();

    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tv_time.setText(time + "");
        }
    };

    private String getConnectWifiSSID() {
        try {
            WifiManager wifimanage=(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            return wifimanage.getConnectionInfo().getSSID().replace("\"", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isFinishing()){
            isRun = false;
            stopQuickSetting();
        }
    }

    public void boolVersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            // 改变titlebar的高度
            int statusbarHeight = BarUtils.getStatusBarHeight(this);
            RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
                    .getLayoutParams();
            layoutParams1.height = statusbarHeight;
            tv_statusBar_mian.setLayoutParams(layoutParams1);
            tv_statusBar_mian.setVisibility(View.VISIBLE);
            //设置状态栏透明
            if (Build.VERSION.SDK_INT >= 21) {
                View decorView = getWindow().getDecorView();
                decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else {
            tv_statusBar_mian.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDeviceWiFiConfigSetted(FunDevice funDevice) {
        if ( null != funDevice ) {
            JSONObject obj = new JSONObject();
            deviceName = funDevice.getDevName();
            try {
                obj.put("classification", "1");
                obj.put("hid", DeviceManager.getInstance().hid);
                obj.put("mainDeviceId", "0");
                obj.put("productId", "7");
                obj.put("deviceAddress", funDevice.getDevSn());
                obj.put("deviceModel", "XM-1");
                obj.put("deviceName", funDevice.getDevName());
                obj.put("deviceType", DeviceType.DEVICE_TYPE_SECURITY_CAMERA + "");
                obj.put("deviceVersion", "1.0");
                obj.put("deviceWifiSSID", getConnectWifiSSID());
                obj.put("deviceId", "0");
                obj.put("key", "10000");
                obj.put("requestTime", "" + System.currentTimeMillis());
                obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
            } catch (JSONException e1) {
                e1.printStackTrace();
            }

            OkHttpUtils.postString().url(HttpURL.UPLOAD_DEVICE_URL)
                    .mediaType(MediaType.parse("application/json;charset=UTF-8"))
                    .content(obj.toString())
                    .build().readTimeOut(5000)
                    .writeTimeOut(5000).connTimeOut(5000)
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Request request, Exception e) {
                            showToast("添加设备失败");
                        }

                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String value = jsonObject.getString("resultCode");
                                if (value.equals("1")) {
                                    showToast("添加设备成功");

                                    isRun = false;
                                    lly_second.setVisibility(View.INVISIBLE);
                                    tv_connecting.setText(deviceName + " 添加成功");

                                    startActivity(MainActivity.class);
                                }else{
                                    showToast("添加设备失败");
                                }
                            } catch (JSONException e) {
                                showToast("数据解析错误");
                                e.printStackTrace();
                            }
                        }
                    });

        }
    }
}
